//
//  CZNetworkTool.swift
//  CY--weiBo
//
//  Created by mac on 15/11/25.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import AFNetworking

//网络请求的枚举
enum CZNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"

}

/// 统一管理错误
enum CZNetworkToolError: Int {
    case EmptyAccessToken = -1
    case EmptyUid = -2
    
    // 属性, 根据不同的枚举类型返回不同的值
    var description: String {
        switch self {
        case .EmptyAccessToken:
            return "AccessToken没有值"
        case .EmptyUid:
            return "Uid没有值"
        }
    }
    
    // 方法, 根据当前类型返回一个NSError
    func error() -> NSError {
        return NSError(domain: "cn.itcast.error.net", code: self.rawValue, userInfo: ["description" : self.description])
    }
}

class CZNetworkTool: AFHTTPSessionManager {
    //单例
    static let sharedInstance: CZNetworkTool = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = CZNetworkTool(baseURL: baseURL)
        //添加响应的序列化器
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    //MARK: - Oauth授权
    //申请应用时分配的Appkey
    private let  client_id = "411809439"
    
    //申请应用时分配的AppSecret
    private let  client_secret = "00256c3d54ec4be5cc7382fcc331ba3e"
    
    //授权回调地址,一定要一样
    let redirect_uri = "http://www.baidu.com/"
    //返回回调授权界面的URL地址
    func oauthURL() -> NSURL {
        //GET方式拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
//        https://api.weibo.com/oauth2/authorize?client_id=411809439&redirect_uri=http://www.baidu.com/
        return NSURL(string: urlString)!
        
    }
    
    //MARK: - 网络工具类加载AccessToken,只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code: String,finished:NetworkCallback) {
        //url地址
        let urlString = "oauth2/access_token"
        //请求参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        //发送POST请求
        request(requestMethod: CZNetworkMethod.POST, urlString: urlString, parameters: parameters, needAccessToken: false, finished: finished)
        
    }
    
    
    
    
    /// MARK: - 获取用户数据
    func loadUserInfo(finished:NetworkCallback) {

        guard let uid = CZUserAccount.loadUserAccount()?.uid
            else {
        
                print("uid 没有值")
                let error = CZNetworkToolError.EmptyUid.error()
                finished(result: nil, error: error)
                return
        }
        let urlString = "2/users/show.json"
        let paramenters = [
//            "access_token": access_token,
            "uid": uid
        ]
        //发送请求 网络工具类只负责加载数据
        request(requestMethod: CZNetworkMethod.GET, urlString: urlString, parameters: paramenters, needAccessToken: true, finished: finished)
        
    }
    
    //MARK: 加载微博数据
    func loadStatus(finished: NetworkCallback)
    {
        let urlString = "http://api.weibo.com/2/statuses/home_timeline.json"
        //参数
        let paraments = [String: AnyObject]()
        
        //调用封装好的GET请求
        let debug = false
        if debug {
            
            //调试,加载本地数据
            loadLocalStatuses(finished)
        }else{
        
            //加载网络数据
            request(requestMethod: CZNetworkMethod.GET, urlString: urlString, parameters: paraments, needAccessToken: true, finished: finished)
        }
        
    }
    
    //将本地的测试微博数据加载进来
    private func loadLocalStatuses(finished:NetworkCallback) {
    
        //获取测试微博数据的路径
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        //从文件加载数据 NSData
        let data = NSData(contentsOfFile: path)!
        
        do{
            let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            //通知调用者获取到了本地数据
            finished(result: json as? [String: AnyObject] , error: nil)
        } catch {
            print("出现了异常")
        }
 
    }
    
    //定义类型别名
    typealias NetworkCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    /**
    抽取AFN GET / POST 方法,网络请求的统一入口都是这个方法
    
    - parameter requestMethod:   请求方式
    - parameter urlString:       url地址
    - parameter parameters:      参数
    - parameter finished:        回调的闭包
    */
    func request(requestMethod requestMethod: CZNetworkMethod,urlString: String,var parameters: [String: AnyObject],needAccessToken: Bool,finished: NetworkCallback) {
        //需要accessToken,就拼接
        if needAccessToken {
            //判断access_token是否存在,存在就拼接,不存在就告诉调用者access_token为空
            guard let access_token = CZUserAccount.loadUserAccount()?.access_token else {
                print("access_token没有值")
//                let error = CZNetworkTool
                let error = CZNetworkToolError.EmptyAccessToken.error()
                finished(result: nil, error: error)
                return
            }
            
            //在参数里面拼接access_token
            parameters["access_token"] = access_token
            
        }
        //准备成功的闭包,在外面只要准备一次,可以传给GET,也可以传给POST
        
        let successCallback = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            // 执行的代码
            finished(result: result as? [String : AnyObject], error: nil)
        }
        //准备失败的闭包
        let failureCallback = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        
        }
        //根据请求方式,发送对应的请求
        switch requestMethod {
        case .GET:
                GET(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        case .POST:
                POST(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        }
        
    }
    
    
    
}
